# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from django.conf import settings
from django.http import HttpResponseRedirect
from django.utils import translation
from django.utils.cache import patch_vary_headers
from sys import maxint

lang_codes = zip(*settings.LANGUAGES)[0]
assert settings.LANGUAGE_CODE in lang_codes, "Check your setting.py: LANGUAGE_CODE must be in LANGUAGES list"

class LocaleFromUrlMiddleware(object):
    """
    Get language from urls like:
    /en-us/some/path/
    /de/some/path/
    etc
    where 'en-us' and 'de' are language codes from settings.LANGUAGES

    When path is similar to /some/path/ (without any code)
    language code taken from settings.LANGUAGE_CODE

    Set current django language and modify request object. Add:

     * request.language_url_prefix
       '' for default language, '/language_code' for others
       Possible usage:
       <a href="{{ request.language_url_prefix }}/">{% trans "Home" %}</a>
       <a href="{{ request.language_url_prefix }}{% url .... %}">...</a>

     * request.path_without_language
       path after '/{lang_code}'

    """
    def process_request(self, request):
        path = request.path
        lang_code = settings.LANGUAGE_CODE

        bits = path.split('/', 2)[1:]
        if len(bits) == 2:
            url_lang_code, url_path = bits
            if url_lang_code in lang_codes:
                lang_code = url_lang_code
                path = '/' + url_path

        translation.activate(lang_code)
        request.path_without_language = path
        if lang_code == settings.LANGUAGE_CODE:
            request.language_url_prefix = ''
        else:
            request.language_url_prefix = '/' + lang_code

    def process_response(self, request, response):
        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = translation.get_language()
        translation.deactivate()
        return response


class LocaleFromUrlMiddleware2(object):  # experimental
    def process_view(self, request, view_func, view_args, view_kwargs):
        lang_code = (view_kwargs.pop('lang', None) or settings.LANGUAGE_CODE).strip('/')
        translation.activate(lang_code)
        if lang_code == settings.LANGUAGE_CODE:
            request.language_url_prefix = ''
            request.path_without_language = request.path
        else:
            request.language_url_prefix = '/' + lang_code
            request.path_without_language = request.path.split(request.language_url_prefix, 1)[-1]

        return view_func(request, *view_args, **view_kwargs)

    def process_response(self, request, response):
        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = translation.get_language()
        translation.deactivate()
        return response



lang_hosts = dict(getattr(settings, 'LANG_HOSTS', ()))
cookie_name = 'redirected_to_another_language'

class RedirectToUserLanguage:
    """
    TODO
    """
    def process_request(self, request):
        if request.COOKIES.get(cookie_name):
            return None

        host = lang_hosts.get(translation.get_language_from_request(request))
        if host and host != request.get_host():
            result = HttpResponseRedirect('http://%s' % host)
            result.set_cookie(
                cookie_name,
                '1',
                max_age=maxint,
                expires=(datetime.today() + timedelta(490)),
                domain=settings.SESSION_COOKIE_DOMAIN,
                path=settings.SESSION_COOKIE_PATH,
                secure=settings.SESSION_COOKIE_SECURE or None
            )
            return result
